import { Modal, Spin, Button, Grid, message, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import { DownloadOutlined, CheckOutlined } from '@ant-design/icons';
import styles from './index.module.scss';

interface WallpaperItem {
    _id: string;
    url: string;
    thumb: string;
    poster?: string;
    raw?: string; // 用于必应壁纸的实际下载链接
}

interface WallpaperModalProps {
    visible: boolean;
    onClose: () => void;
    onSelect: (url: string) => void;
}

type WallpaperSource = 'video' | 'bing' | 'wallhaven'; // 定义壁纸源类型

export default function WallpaperModal({ visible, onClose, onSelect }: WallpaperModalProps) {
    const [wallpapers, setWallpapers] = useState<WallpaperItem[]>([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const { useBreakpoint } = Grid;
    const screens = useBreakpoint();
    const [previewItem, setPreviewItem] = useState<WallpaperItem | null>(null);
    const [activeSource, setActiveSource] = useState<WallpaperSource>('video'); // 当前激活的壁纸源

    // 根据当前源获取API地址
    const getRequestConfig = (pageNum: number) => {
        const baseUrl = 'https://api.codelife.cc';
        switch (activeSource) {
            case 'bing':
                return {
                    url: `${baseUrl}/bing/list?lang=cn&page=${pageNum}&size=16`,
                    headers: {}
                };
            case 'wallhaven':
                return {
                    url: `${baseUrl}/wallpaper/wallhaven?lang=cn&sr=1920x1080&page=${pageNum}&size=16&q=`,
                    headers: {}
                };
            case 'video':
            default:
                return {
                    url: `${baseUrl}/wallpaper/video/list?lang=cn&page=${pageNum}&size=16&sortKey=updateTime`,
                    headers: {
                        'origin': 'chrome-extension://mhloojimgilafopcmlcikiidgbbnelip',
                        'mode': 'itab'
                    }
                };
        }
    };

    // 从API获取壁纸数据
    const fetchWallpapers = async (pageNum: number) => {
        setLoading(true);
        try {
            const { url, headers} = getRequestConfig(pageNum);

            const response = await fetch(url, {
                headers: headers,
            });

            const data = await response.json();
            // if (!response.ok || data.code !== 200) {
            //     return message.error(`获取壁纸数据失败: ${data.msg}`);
            // }

            if (activeSource === 'video' && !data.data) {
                // 必应壁纸的图片地址需要特殊处理
                data.data = [
                    {
                        "_id": "67cecc881c3b536f3e0d8d61",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/88.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/88.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/88.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "67cecbcf954d29cdb0cd759b",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/87.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/87.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/87.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "673e914da4c7abf4f9016172",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/86.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/86.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/86.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "673e9141a4c7abf4f9016171",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/85.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/85.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/85.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "6724ade5c5a00cfc57080af2",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/82.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/82.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/82.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "6724adfac5a00cfc57080af4",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/84.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/84.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/84.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "66c5914b0b21352411923270",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/80.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/80.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/80.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "6724adf0c5a00cfc57080af3",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/83.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/83.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/83.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "6724addbc5a00cfc57080af1",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/81.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/81.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/81.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "669bc17ed37ddd8de91f2ccb",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/79.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/79.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/79.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "66495720ad57705e00f93c14",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/78.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/78.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/78.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "6629197332fc86d689cd9b91",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/77.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/77.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/77.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "660265cc77b1171136d35176",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/76.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/76.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/76.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "660242e9d6f8801722038241",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/75.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/75.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/75.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "644b3827be4db93bda03c2e1",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/v-29.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/v-29.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/v-29.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    },
                    {
                        "_id": "625526ff452009fb7a5febb2",
                        "url": "https://files.codelife.cc/itab/defaultWallpaper/videos/45.mp4",
                        "thumb": "https://files.codelife.cc/itab/defaultWallpaper/videos/45.jpg?x-oss-process=image/resize,limit_0,m_fill,w_400,h_200/quality,q_93/format,webp&a=1.svg",
                        "poster": "https://files.codelife.cc/itab/defaultWallpaper/videos/45.jpg?x-oss-process=image/resize,limit_0,m_fill,w_1920,h_1080/quality,q_93/format,webp"
                    }
                ]
            }

            if (data.data) {
                const formattedData = data.data.map((item: any) => {
                    // 统一不同源的数据格式
                    if (activeSource === 'bing' || activeSource === 'wallhaven') {
                        return {
                            _id: item.id,
                            url: item.raw,
                            thumb: item.thumb,
                            raw: item.raw
                        };
                    }
                    return item;
                });
                setWallpapers(prev => pageNum === 1 ? formattedData : [...prev, ...formattedData]);
                setHasMore(data.data.length > 0);
            }

        } catch (error) {
            message.error('加载壁纸失败: ' + (error as Error).message);
            setHasMore(false);
        } finally {
            setLoading(false);
        }
    };

    // 滚动加载更多
    const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
        const { scrollTop, clientHeight, scrollHeight } = e.currentTarget;
        if (scrollHeight - scrollTop === clientHeight && !loading && hasMore) {
            setPage(prev => prev + 1);
        }
    };

    // 下载壁纸
    const handleDownload = (url: string, e: React.MouseEvent) => {
        e.stopPropagation();
        const downloadUrl = activeSource === 'bing' ? url.replace('&pid=hp', '&pid=download') : url;
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = `wallpaper-${Date.now()}.${activeSource === 'bing' ? 'jpg' : 'mp4'}`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        message.success('开始下载壁纸');
    };

    // 预览壁纸
    const handlePreview = (item: WallpaperItem) => {
        setPreviewItem(item);
    };

    // 重置状态
    const resetState = () => {
        setWallpapers([]);
        setPage(1);
        setHasMore(true);
    };

    // 切换壁纸源
    const handleSourceChange = (key: string) => {
        setActiveSource(key as WallpaperSource);
        resetState();
    };

    useEffect(() => {
        if (visible) {
            resetState();
            fetchWallpapers(1);
        }
    }, [visible, activeSource]); // 当visible或activeSource变化时重新加载

    useEffect(() => {
        if (page > 1) {
            fetchWallpapers(page);
        }
    }, [page]);

    return (
        <>
            <Modal
                title=""
                open={visible}
                onCancel={onClose}
                footer={null}
                width={screens.xl ? '80%' : '90%'}
                style={{ top: 20, caretColor: 'transparent' }}
                destroyOnHidden
            >
                <Tabs
                    activeKey={activeSource}
                    onChange={handleSourceChange}
                    items={[
                        {
                            key: 'video',
                            label: '动态壁纸',
                        },
                        {
                            key: 'bing',
                            label: '必应壁纸',
                        },
                        {
                            key: 'wallhaven',
                            label: 'Wallhaven',
                        },
                    ]}
                />
                <div
                    className={styles.wallpaperGrid}
                    onScroll={handleScroll}
                >
                    {wallpapers.map(item => (
                        <div
                            key={item._id}
                            className={styles.wallpaperItem}
                            onClick={() => handlePreview(item)}
                        >
                            <img
                                src={item.thumb}
                                className={styles.thumbnail}
                                alt="壁纸缩略图"
                                loading="lazy"
                            />
                            <div
                                className={styles.downloadBtn}
                                onClick={(e) => handleDownload(activeSource === 'bing' ? item.raw || item.url : item.url, e)}
                                title="下载到本地"
                            >
                                <DownloadOutlined />
                            </div>
                            <div
                                className={styles.selectBtn}
                                onClick={(e) => {
                                    e.stopPropagation();
                                    onSelect(activeSource === 'bing' ? item.raw || item.url : item.url);
                                }}
                            >
                                <CheckOutlined />
                            </div>
                            <div className={styles.hoverMask} />
                        </div>
                    ))}
                    {loading && (
                        <div className={styles.loadingSpin}>
                            <Spin size="large" />
                        </div>
                    )}
                    {!loading && !hasMore && (
                        <div className={styles.noMoreData}>没有更多壁纸了~</div>
                    )}
                </div>
            </Modal>
            {/* 视频预览弹窗 */}
            {previewItem && (
                <div className={styles.videoPreviewModal}>
                    <div className={styles.videoPreviewContent}>
                        {activeSource === 'video' ? (
                            <video
                                autoPlay
                                muted
                                loop
                                className={styles.videoPlayer}
                                poster={previewItem.poster || previewItem.thumb}
                            >
                                <source src={previewItem.url} type="video/mp4" />
                            </video>
                        ) : (
                            <img
                                src={previewItem.raw || previewItem.url}
                                className={styles.imagePreview}
                                alt="壁纸预览"
                            />
                        )}
                        <button
                            className={styles.closePreviewBtn}
                            onClick={() => setPreviewItem(null)}
                        >
                            ×
                        </button>
                    </div>
                </div>
            )}
        </>
    );
}